package com.jingge.home.service.impl;

import com.jingge.home.framework.CacheKeyConstant;
import com.jingge.home.service.WxMsgHandlerService;
import com.jingge.home.util.LocalCacheManager;
import com.jingge.home.framework.DifyConversationStreamChatClient;
import com.jingge.home.util.SyncHelper;
import com.jingge.home.util.wx.WxMessageBuilder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Yongxiang
 * @date 2025-06-04 14:04
 * @email 1158055613@qq.com
 */
@Slf4j
@Service
public class WxMsgHandlerServiceImpl implements WxMsgHandlerService {
	private static final int MAXIMUM_RETRY_COUNT = 2;
	@Autowired
	private WxCpMessageRouter router;

	@Autowired
	private LocalCacheManager<String, String> msgCache;

	@Override
	public String routeMessage(WxCpXmlMessage message) {
		String content = message.getContent();
		String to = message.getFromUserName();
		String from = message.getToUserName();
		String receiveMsgId = String.valueOf(message.getMsgId());
		String picUrl = message.getPicUrl();
		//如果已经有请求
		if (msgCache.exist(CacheKeyConstant.RECEIVE_MSG_ID_PREFIX + receiveMsgId)) {
			String currentRetryS = msgCache.get(CacheKeyConstant.RETRY_COUNT_PREFIX + receiveMsgId);
			int currentRetry = StringUtils.isEmpty(currentRetryS) ? 1 : Integer.parseInt(currentRetryS) + 1;
			log.info("发现{}已经存在请求，尝试获取缓存消息，这是第{}次重试", receiveMsgId, currentRetry);
			msgCache.set(CacheKeyConstant.RETRY_COUNT_PREFIX + receiveMsgId, String.valueOf(currentRetry));
			SyncHelper.aWaitQuietly(() -> DifyConversationStreamChatClient.isMsgIdFinished(receiveMsgId),
					currentRetry == MAXIMUM_RETRY_COUNT ? 2 : 6, 1000, TimeUnit.SECONDS);
			if (DifyConversationStreamChatClient.isMsgIdFinished(receiveMsgId)) {
				return WxMessageBuilder.toXml(
						WxMessageBuilder.buildTextMessage(msgCache.getAsString(receiveMsgId), from, to));
			}
			String ec = msgCache.getAsString(receiveMsgId);
			return WxMessageBuilder.toXml(WxMessageBuilder.buildTextMessage(
					"{}\n回复\"m\"\n或者\n@{}来获取更多消息",
					from, to, StringUtils.isEmpty(ec) ? "" : ec, receiveMsgId));
		}
		//如果图片不为空
		if (StringUtils.isNotEmpty(picUrl)) {
			msgCache.set(CacheKeyConstant.PIC_PREFIX + to, picUrl, 5, TimeUnit.MINUTES);
			return WxMessageBuilder.toXml(WxMessageBuilder.buildTextMessage(
					"已经收到你的最新的图片啦，你想知道有关这个图片的什么呢？快在五分钟内与我讨论吧", from, to));
		}
		if (StringUtils.isEmpty(content)) {
			return WxMessageBuilder.toXml(WxMessageBuilder.buildTextMessage(
					"您好，欢迎你的关注，我是鲸歌之家的智能助理，请在使用前向管理员获取授权码以开始使用", from, to));
		}
		return WxMessageBuilder.toXml(router.route(message));
	}
}
